from app.view_models.book import BookViewModel


class GiftViewModel(object):
    def __init__(self, gifts, wish_list):
        self.gifts = []
        self.__gifts = gifts
        self.__wish_list = wish_list
        self.gifts = self.__parse()

    def __parse(self):
        # 这里不去直接操作self.gifts,保证类的稳定性,尽量不要再方法内部修改实例属性.
        temp_list = []
        for gift in self.__gifts:
            my_gift = self.__matching(gift)
            temp_list.append(my_gift)
        return temp_list

    def __matching(self, gift):
        # 这个函数的作用是让__parse方法下不用写嵌套循环,把一部分循环的代码放到__matching这个函数中,让代码更优美
        count = 0
        for wish in self.__wish_list:
            if gift.isbn == wish['isbn']:
                count = wish['count']
        # 构建数据
        ret = {
            'id': gift.id,
            'book': BookViewModel(gift.book),
            'wishes_count': count # 书籍存在没人想要的情况,可以为0
        }
        return ret